package com.ly.user_system.lock;


import lombok.RequiredArgsConstructor;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;

import java.util.concurrent.TimeUnit;
import java.util.function.Supplier;

@RequiredArgsConstructor
public class RedisLockService implements LockService {
    private final RedissonClient redissonClient;

    @Override
    public <T> T tryLock(String lockKey, Supplier<T> supplier, long waitTime,  TimeUnit timeUnit) {
        RLock lock = redissonClient.getLock(lockKey);
        T result=null;
        try {
            if (lock.tryLock(waitTime,timeUnit)) {
                try {
                 result=supplier.get();
                } catch (Exception e) {
                    e.printStackTrace();
                    throw new RuntimeException(e);
                }
            }
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }finally {
            if (lock.isLocked()){
                lock.unlock();
            }
            return result;
        }

    }
}
